/////////////////////////////////////////////////////
// workflow for-each


CultureMuncher_Workflow.StepForEach.prototype.init = function(parent, path, text, type) {
	this.level = 0;
    this.children = [];
	this.path = path;
	this.parent = parent;
	this.type = type;
	this.breakPath = this.type == 1;
	
	//this.type = type; // 0: foreach, 1:click
	//this.resetsPath = type != 0;
	
	CultureMuncher_Workflow.parse(text, this);
}

CultureMuncher_Workflow.StepForEach.prototype.addChild = function(child) {
	this.children.push(child);
}

CultureMuncher_Workflow.StepForEach.prototype.toString = function() {
	var cmdName = this.type == 0 ? 'ForEach' : 'Click';
	var tab = ''.padLeft(this.level, '\t');
	var tabch = ''.padLeft(this.level + 1, '\t');
	var text = cmdName + '(' + this.path + ') {\n';
	for (var i=0; i<this.children.length; i++) {
		text += tabch + this.children[i].toString() + '\n';
	}
	text += tab + '}';
	return text;
}

CultureMuncher_Workflow.StepForEach.prototype.getControl = function(doc, parent, ci) {
	var header = this.type == 0 ? 'ForEach: ' : 'Click: ';
	header += this.path;
	var ctrl = CultureMuncher_Workflow.createStepHeader(document, parent, ci, header, '');
	for (var i=0; i<this.children.length; i++) {
		//dump('Creating: ' + this.children[i] + '\r\n');
		ctrl.appendChild(this.children[i].getControl(doc, ctrl, i));
		//dump('Created: ' + this.children[i] + '\r\n');
	}
	
	// color this element
	var pth = CultureMuncher_Workflow.createRootPath(this);
	var elem = selectNodeXPath(content.document, pth);
	if (elem != null) {
		cmWfFrameMaker.getFrame(cmFeIdx++, elem);
	}
	// assign refference to control	
	this.control = ctrl;
	return ctrl;
}

CultureMuncher_Workflow.StepForEach.prototype.run = function(doc, ids, col) {
	// remove indexer
	var pth = this.path;
	var orig = this.path;
	
	if (this.path.charAt(this.path.length - 1) == ']') {
		pth = this.path.substring(0, this.path.lastIndexOf('['));
	}
	var elems = selectNodesXPath(doc, pth);
	
	dump('\n\n=========================================\n');
	dump(this + '\r\n');
	dump('------------------------------------------\n');
	dump('Path: ' + pth + '\n');
	dump('Elements: ' + elems.snapshotLength + '\n')
	dump('=========================================\n');
	
	for ( var i=0 ; i < elems.snapshotLength; i++ ) {
		dump('[' + i + ']\n');
		// skip elements of the new borders
		var elem = elems.snapshotItem(i);
		// temporarily set path
		this.path = get_XPath(elem);
		// run all children
		for (var c=0; c<this.children.length; c++) {
			this.children[c].run(doc, ids, col);
		}
	}
	
	// return to original path
	this.path = orig;
}

/////////////////////////////////////////////////////
// workflow step table

function CmTableAssignment(name, value, format, parser, regex) {
	this.name = name;
	this.value = value == null ? '' : value;
	this.format = format == null ? '' : format;
	this.parser = parser == null ? '' : parser;
	this.regex = regex == null ? '' : regex;
}

CmTableAssignment.prototype.toString = function() {
	return this.name + '=' + this.value + ';' + this.format + ';' + this.parser + ';' + this.regex;
}

CultureMuncher_Workflow.StepTable.prototype.init = function(parent, text) {
	this.tableName = '';
    this.assignments = [];
	var parts = text.split(',');
	
	this.parent = parent;
	this.tableName = parts[0];
	//TODO: Deal with ',' and '='
	for (var i=1; i<parts.length; i++) {
		var couple = parts[i].split('=');
		var vals = couple.length == 2 ? couple[1].split(';') : ['','','',''];
		var ass = new CmTableAssignment(couple[0], vals[0], vals[1], vals[2], vals[3]);
		this.assignments[couple[0]] = ass;
	}
}

CultureMuncher_Workflow.StepTable.prototype.toString = function() {
	var text = 'Use(' + this.tableName + ',';
	var i=0;
	for (var key in this.assignments) {
		if (this.assignments[key] == null) continue;
		if (!(this.assignments[key] instanceof CmTableAssignment)) break;		
		text += this.assignments[key].toString() + ',';
	}
	// remove final ','
	text = text.substring(0, text.length-1);
	text += ')';
	return text;
}

CultureMuncher_Workflow.StepTable.prototype.getControl = function(doc, parent, i) {
	// get definition
	var def = CultureMuncher_Workflow.TableDefinition.factory(this.tableName);
	
	// create header
	var ctrl = CultureMuncher_Workflow.createStepHeader(doc, parent, i, def.name, '');
	
	// now append all lines
	var cols = def.columns;
	
	// rememebr path for this element
	var pth = CultureMuncher_Workflow.createRootPath(this);
	
	for (var line=0; line<cols.length; line++) {		
		// check parent
		var ldef = cols[line];
		
		// we assume all are assignamnets
		var ass = this.assignments[ldef.name];
		var value = ass == null ? '' : ass.value;
		var regex = ass == null ? '' : ass.regex;
		var parser = ass == null ? '' : ass.parser;
		var format = ass == null ? '' : ass.format;
		var id = ctrl.id + "_L" + line;
		var disabled = '';		
		
		// if we need to check the parent
		if (ldef instanceof CultureMuncher_wfTableParent) {
			disabled = "disabled='true'"
			// find if requested parent exists in workflow	
			var srchstp = this;
			var found = false;
			while (srchstp.parent != null) {
				var idx = srchstp.parent.children.indexOf(srchstp) - 1;
				for (var i=idx; i>=0; i--) {
					if (srchstp.parent.children[i] instanceof CultureMuncher_Workflow.StepTable) {
						var pdef = CultureMuncher_Workflow.TableDefinition.factory(srchstp.parent.children[i].tableName);
						if (pdef.tableName == ldef.name) {
							found = true;
						}
						break;
					}
				}
				srchstp = srchstp.parent;
			}	
			if (found) {
				value = "#" + ldef.name + '.' + ldef.id;
			} else if (ldef.strict) {
				value = "#ERROR";
				CultureMuncher_Workflow.isValid = false;
			} 
		}
			
		// append acccording to template
		$(ctrl).append(tableLineTemplate($), {
		     label: ldef.name,
		     text: value,
		     id: id,
		     index: line,
		     regex: regex,
		     parser: parser,
		     format: format,
		     disabled: disabled
		});	
		// possibly hide control
		if (regex == '' && parser == '' && format == '') {
			$('#' + id).hide();
		}
		
		// possibly color this element
		if (value != '' && value.charAt(0) == '/') {
			var pt = pth + value;
			var elem = selectNodeXPath(content.document, pt);
			if (elem != null) {
				cmWtFrameMaker.getFrame(cmTbIdx++, elem);
			}
		}
		
	}
	// assign refference to control	
	this.control = ctrl;
	return ctrl;	
}

CultureMuncher_Workflow.StepTable.prototype.run = function(doc, ids, col) {
	var pth = CultureMuncher_Workflow.createRootPath(this);
	var xpath = '';
	var result = {};
	var ids = [];
	var row = [];
	var ass;
	var elem = null;
	
	dump('\n\n=========================================\n');
	dump('Table: ' + this.tableName + '\n');
	dump('------------------------------------------\n');
	
	for (var key in this.assignments) {
		ass = this.assignments[key];
		
		// array has also some extensions
		if (!(ass instanceof CmTableAssignment)) continue;
		
		dump('Assignment \'' + key + '\': ' + ass.value + '\n');
		
		// we can have path
		if (ass.value.charAt(0) == '/') {
			xpath = pth + ass.value;
			elem = selectNodeXPath(doc, xpath);
			row[ass.name] = elem.innerHTML;
		}
		// or id 
		else if (ass.value.charAt(0) == '#') {
			
		} else {
			row[ass.name] = ass.value;
		}
		dump('Value: ' + row[ass.name] + '\n');
	} 
	dump('=========================================\n');
	result.row = row;
	result.ids = ids;
	
	if (col[this.tableName] == null) {
		col[this.tableName] = new Array();
	}
	col[this.tableName].push(row);
}


/////////////////////////////////////////////////////
// workflow step click

// CultureMuncher_Workflow.StepClick.prototype.init = function(parent, text) {
	// this.parent = parent;
	// this.elementPath = text;
	// this.elementPath = '';
// }
// 
// CultureMuncher_Workflow.StepClick.prototype.toString = function() {
	// return 'Click(' + this.elementPath + ')';
// }
// 
// CultureMuncher_Workflow.StepClick.prototype.getControl = function(doc, parent, i) {
	// var ctrl = CultureMuncher_Workflow.createStepHeader(doc, parent, i, 'Click:' + this.path, '');	
	// // assign refference to control	
	// this.control = ctrl;
	// return ctrl;
// }
// 
// CultureMuncher_Workflow.StepClick.prototype.run = function(doc, ids, ctrl) {
	// dump('Click changes document!!');
// }

/////////////////////////////////////////////////////
// enum


CultureMuncher_WorkflowStep = {
    ForEach: 0,
    Table: 1,
    Click: 2
}